import router from './router'

//引入nprogress
import NProgress from 'nprogress'
//引入nprogress的样式
import 'nprogress/nprogress.css'
//自定义nprogress进度条颜色
import './styles/custom-nprogress/index.css'
//取消nprogress的加载进度条
NProgress.configure({ showSpinner: false })

//引入pinia
import pinia from './store'
//获取用户相关的小仓库内部username，判断是否登录.
import useUserStore from './store/modules/user'
let userStore = useUserStore(pinia)
//获取用户名字
let username = userStore.username

//引入项目配置文件
import setting from './setting'
//引入获取token的函数
import { GET_TOKEN } from './utils/token'

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  //获取token,直接从本地存储中获取
  const token = GET_TOKEN()
  //判断token是否存在
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        //获取用户信息，判断用户名是否存在
        try {
          await userStore.getUserInfo()
          // console.log('获取用户信息', result)
          next()
        } catch (error) {
          //token过期或者用户手动修改本地存储token
          //清除token
          userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    //这个if必须要有，否则会陷入路由死循环！！！
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
//全局后置守卫
router.afterEach((to, from) => {
  //页面标题
  document.title = `${setting.title} - ${to.meta.title}`
  NProgress.done()
})
